package com.gw.quotes.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gw.quotes.R;
import com.gw.quotes.entity.business.ProjectInfoEntity.ProjectInfo;
import com.gw.quotes.entity.business.ProjectListEntity.ProjectItem.ProjectGood;
import com.gw.quotes.entity.business.ProjectListEntity.ProjectItem.ProjectGood.Projectaccessorie;
import com.gw.quotes.entity.business.QuoteEntity;
import com.gw.quotes.entity.business.QuoteEntity.Accquotation;
import com.gw.quotes.net.BaseServiceInter;
import com.gw.quotes.net.HttpCallBack;
import com.gw.quotes.net.Request;
import com.gw.quotes.net.Response;
import com.gw.quotes.net.service.ProjectSaveQuotationServiceImpl;
import com.gw.quotes.util.CommonTools;
import com.yxw.util.StringUtils;
import com.yxw.view.NoScrollListView;

public class QuoteDetailQuotingActivity extends BaseActivity {

	@ViewInject(id = R.id.back_img, click = "back")
	private ImageView back_img;
	@ViewInject(id = R.id.layout_quote)
	private RelativeLayout layout_quote;
	@ViewInject(id = R.id.nolistview)
	private NoScrollListView nolistview;
	@ViewInject(id = R.id.text_agreementprice)
	private TextView text_agreementprice;
	@ViewInject(id = R.id.text_total_pric)
	private TextView text_total_pric;
	@ViewInject(id = R.id.text_total_pric_last)
	private TextView text_total_pric_last;
	@ViewInject(id = R.id.text_peijian_list)
	private TextView text_peijian_list;

	@ViewInject(id = R.id.et_agreementprice)
	private EditText et_agreementprice;

	@ViewInject(id = R.id.bt_quote_submit, click = "submit")
	private Button bt_quote_submit;

	// 适配器
	private QuoteAdapter quoteAdapter;

	// 参数
	private ProjectInfo projectInfo;

	/**
	 * 得到获取网络时间时的手机当前时间 用于计算时间偏移量
	 */
	private long cur_sys_time;
	/**
	 * 获取网络当前时间
	 */
	private long cur_net_time;
	/**
	 * 截至时间
	 */
	private long end_time;
	
	/** 上次总报价 */
	private double totalPricLast;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_quote_quoting);
		getIntentData();
		initView();
	}

	private void getIntentData() {
		Intent intent = getIntent();
		projectInfo = (ProjectInfo) intent.getSerializableExtra("projectInfo");
		cur_net_time = intent.getLongExtra("cur_net_time", Long.MAX_VALUE);
		cur_sys_time = intent.getLongExtra("cur_net_time", Long.MAX_VALUE);
		end_time = intent.getLongExtra("end_time", Long.MIN_VALUE);
		totalPricLast = intent.getDoubleExtra("totalPric_last", Double.MIN_VALUE);
	}

	private void initView() {
		ProjectGood projectGood = projectInfo.getProjectGoodList().get(0);
		text_agreementprice.setText(projectGood.getGoodsname()+" * "+projectInfo.getQty());
		et_agreementprice.setText(String.format("%.2f", projectGood.getAgreementprice()));
		// 没有配件时，隐藏配件列表
		if (projectGood.getProjectaccessorieList() == null
				|| projectGood.getProjectaccessorieList().size() == 0) {
			text_peijian_list.setVisibility(View.GONE);
		}
		quoteAdapter = new QuoteAdapter();
		nolistview.setAdapter(quoteAdapter);
		getTotalPric();
		et_agreementprice.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				getTotalPric();
			}
		});
	}

	/**
	 * 报价request
	 */
	private void requestInfo() {
		QuoteEntity entity;
		if ((entity = getData()) != null) {// 填写报价正确时
			dialog.show();
			BaseServiceInter httpService = new ProjectSaveQuotationServiceImpl();
			Request request = new Request();
			Gson gson = new Gson();
			request.setQutationjson(gson.toJson(entity));
			request.setProjecttype(projectInfo.getProjecttype());
			request.setLoginname(getLoginUser().getLoginname());
			request.setTicket(getLoginUser().getTicket());
			Response response = httpService.handler(request,
					new HttpCallBack<Response>() {
						@Override
						public void onFinished(Response response) {
							if (response.getResult() == Response.RESULT_SUCCESS) {
								CommonTools.showShortToast(
										QuoteDetailQuotingActivity.this,
										"恭喜你，报价成功！");
								setResult(2);
								finish();
							} else {
								CommonTools.showShortToast(
										QuoteDetailQuotingActivity.this,
										response.getMsg());
							}
							dialog.dismiss();
						}
					});
		} else {
			CommonTools.showShortToast(QuoteDetailQuotingActivity.this,
					"报价失败，请重试！");
		}
	}

	/**
	 * 获取报价的价格
	 * 
	 * @return
	 */
	private QuoteEntity getData() {
		QuoteEntity entity = new QuoteEntity();
		entity.setProjectguid(projectInfo.getProjectguid());
		entity.setProjectgoodsguid(projectInfo.getProjectGoodList().get(0)
				.getProjectgoodsguid());
		if (StringUtils.isEmpty(et_agreementprice.getText() + "")) {
			entity.setPrice(0);
		} else {
			entity.setPrice(Double.parseDouble(et_agreementprice.getText()+""));// 原
			
			// 格式化
			if(et_agreementprice.getText() != null && !"".equals(et_agreementprice.getText())){
				String et_agreementpriceText = et_agreementprice.getText().toString();
				entity.setPrice(Double.parseDouble(String.format("%.2f",Double.valueOf(et_agreementpriceText))));// 配件价格提交
			}else{
				entity.setPrice(0);
			}
		}

		List<Accquotation> accquotations = new ArrayList<QuoteEntity.Accquotation>();
		for (int i = 0; i < nolistview.getChildCount(); i++) {
			View view = nolistview.getChildAt(i);
			EditText et_price = (EditText) view.findViewById(R.id.et_price);
			// if (StringUtils.isEmpty(et_price.getText() + "")) {
			// return null;
			// }
			Accquotation accquotation = new Accquotation();
			accquotation.setProjectaccessoryguid(projectInfo
					.getProjectGoodList().get(0).getProjectaccessorieList()
					.get(i).getProjectaccessoryguid());
			if (StringUtils.isEmpty(et_price.getText() + "")) {
				accquotation.setPrice(0.00);
			} else {
				accquotation.setPrice(Double.parseDouble(et_price.getText()+""));// 原
				
				// 格式化
				if(et_price.getText() != null && !"".equals(et_price.getText())){
					String et_priceText = et_price.getText().toString();
					accquotation.setPrice(Double.parseDouble(String.format("%.2f",Double.valueOf(et_priceText))));// 商品价格提交
				}else{
					accquotation.setPrice(0.00);
				}
			}
			accquotations.add(accquotation);
		}
		entity.setAccquotations(accquotations);
		return entity;
	}

	/**
	 * 计算总价
	 */
	private void getTotalPric() {
		QuoteEntity entity = getData();
		double totalPric = 0;
		if (entity != null) {
			totalPric += entity.getPrice() * projectInfo.getQty();
			for (int i = 0; i < entity.getAccquotations().size(); i++) {
				totalPric += entity.getAccquotations().get(i).getPrice()
						* projectInfo.getProjectGoodList().get(0)
								.getProjectaccessorieList().get(i).getQty();
			}
		}
		text_total_pric.setText(String.format("总价：%.2f", totalPric));
		if(totalPricLast!=0){
			text_total_pric_last.setText(String.format("上次报价：%.2f", totalPricLast));
		}else{
			text_total_pric_last.setText("");
		}
	}

	public void back(View v) {
		finish();
	}

	public void submit(View v) {
		if (end_time > cur_net_time + (new Date().getTime() - cur_sys_time)) {
			requestInfo();
		} else {
			CommonTools.showShortToast(this, "抱歉，已超过报价截止时间！");
			this.finish();
		}
	}

	class QuoteAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			try {
				return projectInfo.getProjectGoodList().get(0)
						.getProjectaccessorieList().size();
			} catch (Exception e) {
				return 0;
			}

		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			try {
				return projectInfo.getProjectGoodList().get(0)
						.getProjectaccessorieList().get(position);
			} catch (Exception e) {
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			try {
				return projectInfo.getProjectGoodList().get(0)
						.getProjectaccessorieList().size();
			} catch (Exception e) {
				return 0;
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.item_quote_quoting, null);
			}
			Projectaccessorie projectaccessorie = (Projectaccessorie) getItem(position);
			TextView item_title = (TextView) convertView
					.findViewById(R.id.item_title);
			EditText et_price = (EditText) convertView
					.findViewById(R.id.et_price);
			et_price.setText(String.format("%.2f", projectaccessorie.getAgreementprice()));
			et_price.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					getTotalPric();
				}
			});
			item_title.setText(projectaccessorie.getGoodsname()+" * "+projectaccessorie.getQty());
			return convertView;
		}

	}
}

